<template>
  <div class="login-container">
    <!-- 背景装饰 -->
    <div class="background-decoration">
      <div class="bubble bubble-1"></div>
      <div class="bubble bubble-2"></div>
      <div class="bubble bubble-3"></div>
      <div class="bubble bubble-4"></div>
    </div>

    <div class="login-card">
      <!-- 系统Logo和标题 -->
      <div class="login-header">
        <div class="logo">
          <el-icon size="48" color="#409EFF">
            <House />
          </el-icon>
        </div>
        <h1>洗护管理系统</h1>
        <p>专业的洗护服务管理平台</p>
      </div>

      <!-- 管理员登录提示 -->
      <div class="admin-notice">
        <el-alert
          title="管理员登录"
          description="此系统仅限管理员使用，请使用管理员账号登录"
          type="info"
          :closable="false"
          show-icon
        />
      </div>

      <!-- 登录表单 -->
      <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login-form">
        <el-form-item prop="phone">
          <el-input
            v-model="loginForm.phone"
            placeholder="请输入手机号"
            prefix-icon="Phone"
            size="large"
            clearable
            @keyup.enter="handleLogin"
          >

          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            size="large"
            show-password
            clearable
            @keyup.enter="handleLogin"
          />
        </el-form-item>

        <!-- 验证码（可选） -->
        <el-form-item v-if="showCaptcha" prop="captcha">
          <div class="captcha-container">
            <el-input
              v-model="loginForm.captcha"
              placeholder="请输入验证码"
              prefix-icon="Key"
              size="large"
              style="flex: 1; margin-right: 10px;"
              @keyup.enter="handleLogin"
            />
            <div class="captcha-image" @click="refreshCaptcha">
              <span>{{ captchaText }}</span>
            </div>
          </div>
        </el-form-item>

        <el-form-item>
          <div class="form-options">
            <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
            <el-link type="primary" @click="showForgotPassword = true">
              忘记密码？
            </el-link>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            style="width: 100%"
            :loading="loading"
            @click="handleLogin"
          >
            <el-icon style="margin-right: 5px;"><User /></el-icon>
            登 录
          </el-button>
        </el-form-item>


      </el-form>



      <div class="login-footer">
        <p>洗护管理系统 v1.0 - 专业的洗护服务管理平台</p>
        <div class="footer-links">
          <el-link type="info" size="small">服务条款</el-link>
          <el-divider direction="vertical" />
          <el-link type="info" size="small">隐私政策</el-link>
          <el-divider direction="vertical" />
          <el-link type="info" size="small">帮助中心</el-link>
        </div>
      </div>
    </div>

    <!-- 忘记密码对话框 -->
    <el-dialog v-model="showForgotPassword" title="忘记密码" width="400px">
      <el-form :model="forgotForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="forgotForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="forgotForm.email" placeholder="请输入邮箱地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showForgotPassword = false">取消</el-button>
        <el-button type="primary" @click="handleForgotPassword">发送重置邮件</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  User,
  Lock,
  UserFilled,
  InfoFilled,
  Key,
  House
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

const loginFormRef = ref()
const loading = ref(false)
const showCaptcha = ref(false)

const showForgotPassword = ref(false)
const captchaText = ref('ABCD')

const loginForm = reactive({
  phone: '',
  password: '',
  captcha: '',
  rememberMe: false,
  userType: ''
})

const forgotForm = reactive({
  username: '',
  email: ''
})

const loginRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 20, message: '密码长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  captcha: [
    { required: false, message: '请输入验证码', trigger: 'blur' },
    { len: 4, message: '验证码长度为4位', trigger: 'blur' }
  ]
}

// 管理员角色验证
const validateAdminRole = (userRole) => {
  const allowedRoles = ['ADMIN', 'admin']
  return allowedRoles.includes(userRole)
}



// 刷新验证码
const refreshCaptcha = () => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
  let result = ''
  for (let i = 0; i < 4; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  captchaText.value = result
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return

  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      // 验证码检查（如果启用）
      if (showCaptcha.value && loginForm.captcha.toUpperCase() !== captchaText.value) {
        ElMessage.error('验证码错误')
        refreshCaptcha()
        return
      }

      loading.value = true
      try {
        // 使用用户store进行登录
        const result = await userStore.login({
          phone: loginForm.phone,
          password: loginForm.password
        })

        if (result.success) {
          // 验证用户角色 - 只允许管理员登录
          const userRole = result.data?.user?.role || result.user?.role || 'CUSTOMER'

          if (!['ADMIN', 'admin', 'SUPER_ADMIN', 'super_admin'].includes(userRole)) {
            ElMessage.error('此系统仅限管理员使用，请联系系统管理员')
            userStore.logout()
            return
          }

          // 记住我功能
          if (loginForm.rememberMe) {
            localStorage.setItem('rememberPhone', loginForm.phone)
          } else {
            localStorage.removeItem('rememberPhone')
          }

          ElMessage.success('管理员登录成功，欢迎回来！')

          // 使用页面跳转确保状态完全刷新
          setTimeout(() => {
            window.location.href = '/dashboard'
          }, 500)
        } else {
          ElMessage.error(result.message || '登录失败')
          // 登录失败3次后显示验证码
          const failCount = parseInt(localStorage.getItem('loginFailCount') || '0') + 1
          localStorage.setItem('loginFailCount', failCount.toString())
          if (failCount >= 3) {
            showCaptcha.value = true
            refreshCaptcha()
          }
        }
      } catch (error) {
        console.error('登录失败:', error)
        ElMessage.error(error.message || '登录失败，请检查用户名和密码')

        // 登录失败处理
        const failCount = parseInt(localStorage.getItem('loginFailCount') || '0') + 1
        localStorage.setItem('loginFailCount', failCount.toString())
        if (failCount >= 3) {
          showCaptcha.value = true
          refreshCaptcha()
        }
      } finally {
        loading.value = false
      }
    }
  })
}

// 移除注册功能 - 管理员系统不需要注册

// 处理忘记密码
const handleForgotPassword = async () => {
  if (!forgotForm.username || !forgotForm.email) {
    ElMessage.warning('请填写完整信息')
    return
  }

  try {
    // 这里调用忘记密码API
    ElMessage.success('重置密码邮件已发送，请查收邮箱')
    showForgotPassword.value = false
  } catch (error) {
    ElMessage.error('发送失败，请稍后重试')
  }
}

// 页面加载时检查记住的手机号
onMounted(() => {
  const rememberedPhone = localStorage.getItem('rememberPhone')

  if (rememberedPhone) {
    loginForm.phone = rememberedPhone
    loginForm.rememberMe = true
  }

  // 移除用户类型记忆功能

  // 清除登录失败计数（页面刷新时）
  localStorage.removeItem('loginFailCount')

  // 初始化验证码
  refreshCaptcha()
})
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;

  // 背景装饰
  .background-decoration {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;

    .bubble {
      position: absolute;
      border-radius: 50%;
      background: rgba(255, 255, 255, 0.1);
      animation: float 6s ease-in-out infinite;

      &.bubble-1 {
        width: 80px;
        height: 80px;
        top: 10%;
        left: 10%;
        animation-delay: 0s;
      }

      &.bubble-2 {
        width: 120px;
        height: 120px;
        top: 20%;
        right: 10%;
        animation-delay: 2s;
      }

      &.bubble-3 {
        width: 60px;
        height: 60px;
        bottom: 20%;
        left: 20%;
        animation-delay: 4s;
      }

      &.bubble-4 {
        width: 100px;
        height: 100px;
        bottom: 10%;
        right: 20%;
        animation-delay: 1s;
      }
    }
  }

  .login-card {
    width: 450px;
    max-width: 90vw;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    padding: 40px;
    position: relative;
    z-index: 1;

    .login-header {
      text-align: center;
      margin-bottom: 30px;

      .logo {
        margin-bottom: 15px;
      }

      h1 {
        font-size: 28px;
        color: #333;
        margin-bottom: 10px;
        font-weight: 600;
      }

      p {
        color: #666;
        font-size: 14px;
      }
    }

    .admin-notice {
      margin-bottom: 25px;

      .el-alert {
        border-radius: 8px;
      }
    }

    .login-form {
      .el-form-item {
        margin-bottom: 20px;
      }

      .info-icon {
        color: #909399;
        cursor: help;
      }

      .captcha-container {
        display: flex;
        align-items: center;

        .captcha-image {
          width: 100px;
          height: 40px;
          background: linear-gradient(45deg, #f0f0f0, #e0e0e0);
          border: 1px solid #dcdfe6;
          border-radius: 4px;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          font-weight: bold;
          color: #333;
          user-select: none;

          &:hover {
            background: linear-gradient(45deg, #e0e0e0, #d0d0d0);
          }
        }
      }

      .form-options {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
    }

    .test-accounts {
      margin-top: 20px;

      .account-list {
        .account-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 8px 12px;
          margin-bottom: 5px;
          background: #f8f9fa;
          border-radius: 6px;
          cursor: pointer;
          transition: all 0.3s;

          &:hover {
            background: #e9ecef;
            transform: translateX(5px);
          }

          .role {
            font-weight: 500;
            color: #495057;
          }

          .credentials {
            font-size: 12px;
            color: #6c757d;
            font-family: monospace;
          }
        }
      }
    }

    .login-footer {
      text-align: center;
      margin-top: 30px;

      p {
        color: #999;
        font-size: 12px;
        margin-bottom: 10px;
      }

      .footer-links {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 5px;
      }
    }
  }
}

// 动画
@keyframes float {
  0%, 100% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-20px);
  }
}

// 响应式设计
@media (max-width: 768px) {
  .login-container {
    padding: 20px;

    .login-card {
      width: 100%;
      padding: 30px 20px;
    }
  }

  .test-accounts {
    .test-notice {
      text-align: center;
      color: #f56c6c;
      font-size: 12px;
      margin-top: 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 5px;
    }
  }
}
</style>